package com.dxiang.demo.service;

import com.dxiang.demo.common.Constants;
import com.dxiang.demo.common.Global;
import com.dxiang.demo.common.Token;
import com.dxiang.demo.model.Account;
import com.dxiang.demo.utils.JedisManager;

/**
 * @author Jerry
 */
public class TokenService {
	
    private static long expires;
    private static long TEMP_EXPIRES;
    
    private static TokenService instance = new TokenService();

	static {
		String expirStr = Global.getConfig("token.expires", Constants.TOKEN_EXPIRES_DEFAULT + "");
		String tempExpirStr = Global.getConfig("token.tempExpires", Constants.TOKEN_TEMP_EXPIRES_DEFAULT + "");
        expires = Long.valueOf(expirStr) * 24 * 3600;//s
        TEMP_EXPIRES = Long.valueOf(tempExpirStr)*24*3600;
	}

	private TokenService(){}
	
	public static TokenService getInstance(){
		return instance;
	}
	
	/**
	 * 生成 token
	 * @param account
	 * @return
	 */
	public Token getToken(Account account){
		Token token = TokenProvider.getInstance().createToken(account);
		JedisManager.getInstance().set(Constants.REDIS_DB_TOKEN, token.getToken(), token, expires);
		return token;
	}
	
	/**
	 * 生成临时 token
	 * @param account
	 * @return
	 */
	public Token getTempToken(Account account){
		Token token = TokenProvider.getInstance().createToken(account);
		JedisManager.getInstance().set(Constants.REDIS_DB_TOKEN, token.getToken(), token, TEMP_EXPIRES);
		return token;
	}
	
	/**
	 * 刷新token
	 * @param token
	 * @return
	 */
    public Token updateToken(Token token){
    	JedisManager.getInstance().set(Constants.REDIS_DB_TOKEN, token.getToken(), token, expires);
        return token;
    }
    
    /**
     * 查询token
     * @param tokenStr
     * @return
     */
    public Token findToken(String tokenStr){
        Token token = (Token) JedisManager.getInstance().get(Constants.REDIS_DB_TOKEN, tokenStr, Token.class);
        return token;  
    }
    
    /**
     * remove token
     * @param tokenStr
     */
    public void clearToken(String tokenStr) {
    	JedisManager.getInstance().Del(Constants.REDIS_DB_TOKEN, tokenStr);
    }    
    
    /**
     * 
     * @param token
     * @param account
     * @return
     */
    public boolean validateToken(Token token, Account account){
        return TokenProvider.getInstance().validateToken(token, account);
    }
    
    /**
     * 
     * @param authToken
     * @return
     */
    public String getUserIdFromToken(String authToken) {
        Token token = findToken(authToken);
    	return token.getUid().toString();
    }
    
    public boolean expires(String authToken) {
        Token token = findToken(authToken);
        if (token == null)
            return true;
    	return TokenProvider.getInstance().expires(token);
    }
    
    public boolean expires(Token token) {
        return TokenProvider.getInstance().expires(token);
    }
    
}  